package com.rainwood.material.uitls;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import com.rainwood.material.App;

/**
 * @auther : hhx
 * @date :  2021/3/4
 * @des :
 */
public class ToastUtils {

    private static Toast toast = null;
    private static Handler mainHandler = new Handler(Looper.getMainLooper());
    private static int duration = Toast.LENGTH_SHORT;

    public static void show(int id) {
        String resourcesString = ToolUtils.getResourcesString(App.getInstance(), id);
        show(resourcesString);
    }

    public static void show(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            showInternal(str);
        } else {
            mainHandler.post(() -> {
                show(str);
            });
        }
    }

    private static void showInternal(String str) {
        createToastIfNeeded();
        toast.setText(str);
        toast.show();
    }

    private static void createToastIfNeeded() {
        if (toast == null) {
            toast = Toast.makeText(App.getInstance(), "", duration);
        }
    }


}
